import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:stop_watch_timer/stop_watch_timer.dart';
import 'package:yp/config/index.dart';
import 'package:yp/config/style.dart';
import 'package:yp/helper.dart';
import 'package:yp/util/util.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/index.dart';

typedef ClickCallback = void Function(int selectIndex, String selectString,
    {Map<String, dynamic> info});

typedef Callback = void Function();

class YpShowDialog {
  static void dialog(BuildContext context, Widget content,
      {bool bottom, EdgeInsetsGeometry padding}) {
    showDialog(
        context: context,
        // 点击空白收
        // barrierDismissible: false,
        builder: (BuildContext context) {
          return Padding(
            padding: padding ?? const EdgeInsets.symmetric(horizontal: 25),
            child: Material(
                type: MaterialType.transparency,
                child: Center(
                  child: content,
                )),
          );
        });
  }

  ///弹框
  static void normalConfirm(BuildContext context, String title,
      {String content,
      Function rightCallback,
      Function leftCallback,
      //正常顺序，true 取消 确认，false 确认 取消
      bool normalOrder = true,
      String btnRightText,
      String btnLeftText}) async {
    btnLeftText ??= normalOrder ? '取消' : '确认';
    btnRightText ??= normalOrder ? '确认' : '取消';
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return SimpleDialog(
            titlePadding: const EdgeInsets.only(top: 48.0),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(10)),
            ),
            title: Center(
              child: Text(
                title,
                style: TextStyle(
                    fontSize: EsSizes.MD, color: EsColors.TitleSecondary),
              ),
            ),
            children: <Widget>[
              Offstage(
                  offstage: content == null,
                  child: Center(
                      child: Text(
                    content ?? '',
                    style: TextStyle(
                        fontSize: EsSizes.SM,
                        color: EsColors.ContentSecondary,
                        fontWeight: EsFontWeights.Normal),
                  ))),
              Padding(
                padding: EdgeInsets.only(
                    left: 20, right: 20, top: content == null ? 50 : 20),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      child: FlatButton(
                        child: Text(
                          btnLeftText,
                          style: TextStyle(
                              fontSize: EsSizes.SM, color: Color(0xffb7bdd2)),
                        ),
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        color: Color(0xfff8f8fa),
                        onPressed: () {
                          Navigator.of(context).pop();
                          if (leftCallback != null) {
                            leftCallback();
                          }
                        },
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(20))),
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                      child: FlatButton(
                        color: EsColors.Primary,
                        child: Text(btnRightText,
                            style: TextStyle(
                                fontSize: EsSizes.SM, color: EsColors.White)),
                        padding: const EdgeInsets.symmetric(vertical: 10),
                        onPressed: () {
                          Navigator.of(context).pop();
                          if (rightCallback != null) {
                            rightCallback();
                          }
                        },
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(20))),
                      ),
                    ),
                  ],
                ),
              )
            ],
          );
        });
  }

  ///  自提
  static void showPickUpStation(
      BuildContext context, List info, ClickCallback clickCallback) {
    int selectIndex;
    for (var i = 0; i < info.length; i++) {
      if (info[i]['isSelect']) {
        selectIndex = i;
      }
    }

    showDialog(
        context: context,
        // 点击空白收
        // barrierDismissible: false,
        builder: (BuildContext context) {
          return StatefulBuilder(builder: (context1, state1) {
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 25),
              child: Material(
                  type: MaterialType.transparency,
                  child: Center(
                    child: IntrinsicHeight(
                      child: Container(
                        decoration: BoxDecoration(
                            color: EsColors.White,
                            borderRadius: BorderRadius.circular(10)),
                        child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              SizedBox(height: 18),
                              Text('选择自提点',
                                  style: TextStyle(
                                      fontSize: EsSizes.SM,
                                      color: EsColors.Content,
                                      fontWeight: EsFontWeights.Normal),
                                  textAlign: TextAlign.center),
                              Container(
                                height:
                                    (info.length > 4 ? 4 : info.length) * 60.0,
                                child: ListView.separated(
                                    shrinkWrap: true,
                                    padding: EdgeInsets.zero,
                                    itemBuilder: (context, index) {
                                      return GestureDetector(
                                        behavior: HitTestBehavior.opaque,
                                        onTap: () {
                                          state1(() {
                                            print('切换自选地点');

                                            for (var i = 0;
                                                i < info.length;
                                                i++) {
                                              if (i == index) {
                                                info[i]['isSelect'] = true;
                                                selectIndex = index;
                                              } else {
                                                info[i]['isSelect'] = false;
                                              }
                                            }
                                          });
                                        },
                                        child: Padding(
                                          padding: const EdgeInsets.symmetric(
                                              horizontal: 12, vertical: 20),
                                          child: Row(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.center,
                                            children: [
                                              Image.asset(
                                                  info[index]['isSelect']
                                                      ? 'assets/images/selectIcon1.png'
                                                      : 'assets/images/select1.png',
                                                  width: 18,
                                                  height: 18),
                                              SizedBox(width: 8),
                                              Expanded(
                                                child: Column(
                                                  crossAxisAlignment:
                                                      CrossAxisAlignment.start,
                                                  children: [
                                                    Visibility(
                                                      visible: info[index]
                                                                  ['name'] !=
                                                              null &&
                                                          info[index]['name'] !=
                                                              '',
                                                      child: Padding(
                                                        padding:
                                                            const EdgeInsets
                                                                    .only(
                                                                bottom: 8),
                                                        child: Text(
                                                          info[index]['name'],
                                                          style: TextStyle(
                                                              color: EsColors
                                                                  .Title,
                                                              fontSize:
                                                                  EsSizes.SM,
                                                              fontWeight:
                                                                  EsFontWeights
                                                                      .Medium),
                                                        ),
                                                      ),
                                                    ),
                                                    Text(
                                                      '上海市静安区万航路889号越大广航芜湖起飞B1-902室',
                                                      style: TextStyle(
                                                          color:
                                                              EsColors.Content,
                                                          fontSize: EsSizes.SM,
                                                          fontWeight:
                                                              EsFontWeights
                                                                  .Normal),
                                                    ),
                                                  ],
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                      );
                                    },
                                    separatorBuilder: (context, index) =>
                                        YpLine(),
                                    itemCount: info.length),
                              ),
                              EsBottomWidget(
                                  leftTitle: null,
                                  rightTitle: '确定',
                                  rightlick: () {
                                    if (selectIndex != null) {
                                      print('确定');
                                      Navigator.of(context).pop();
                                      clickCallback(selectIndex,
                                          info[selectIndex]['name'],
                                          info: {});
                                    } else {
                                      showToast('请选择自提点');
                                    }
                                  },
                                  decoration: null)
                            ]),
                      ),
                    ),
                  )),
            );
          });
        });
  }

  /// 完善会员奖励
  static void showCompleteMemberReward(BuildContext context,
      {List info, ClickCallback clickCallback}) {
    YpShowDialog.dialog(
        context,
        Container(
          width: double.infinity,
          height: 235,
          margin: const EdgeInsets.symmetric(horizontal: 20),
          padding: const EdgeInsets.symmetric(horizontal: 30, vertical: 25),
          alignment: Alignment.center,
          decoration: EsDecoration.BoxShadowWithRadius,
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  '恭喜您获得以下奖励',
                  style: TextStyle(
                      fontSize: EsSizes.XL,
                      color: EsColors.Primary,
                      fontWeight: EsFontWeights.Medium),
                ),
                SizedBox(height: 6),
                RichText(
                  text: TextSpan(children: [
                    _buildCenteredTextSpan(
                        text: '积分',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Title,
                            fontWeight: EsFontWeights.Normal)),
                    _buildCenteredTextSpan(
                        text: '+20',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Pink,
                            fontWeight: EsFontWeights.Normal)),
                  ]),
                ),
                RichText(
                  text: TextSpan(children: [
                    _buildCenteredTextSpan(
                        text: '成长值',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Title,
                            fontWeight: EsFontWeights.Normal)),
                    _buildCenteredTextSpan(
                        text: '+20',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Pink,
                            fontWeight: EsFontWeights.Normal)),
                  ]),
                ),
                RichText(
                  text: TextSpan(children: [
                    _buildCenteredTextSpan(
                        text: '优惠券',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Title,
                            fontWeight: EsFontWeights.Normal)),
                    _buildCenteredTextSpan(
                        text: 'x3张',
                        width: 50,
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Pink,
                            fontWeight: EsFontWeights.Normal)),
                  ]),
                ),
                Expanded(child: SizedBox(height: 20)),
                Padding(
                  padding: const EdgeInsets.only(top: 0, bottom: 18),
                  child: RichText(
                    textAlign: TextAlign.center,
                    text: TextSpan(
                        text: '奖品详情请于',
                        style: TextStyle(
                            fontSize: EsSizes.SM,
                            color: EsColors.Title,
                            fontWeight: EsFontWeights.Normal),
                        children: <TextSpan>[
                          TextSpan(
                              text: '我的奖励',
                              style: TextStyle(
                                  fontSize: EsSizes.SM,
                                  color: EsColors.Primary,
                                  fontWeight: EsFontWeights.Normal),
                              recognizer: TapGestureRecognizer()
                                ..onTap = () {
                                  print('我的奖励');
                                  Navigator.of(context).pop();
                                }),
                          TextSpan(
                              text: '中查看',
                              style: TextStyle(
                                  fontSize: EsSizes.SM,
                                  color: EsColors.Title,
                                  fontWeight: EsFontWeights.Normal)),
                        ]),
                  ),
                ),
                Center(
                  child: EsOutLineButton(
                    '好的',
                    padding: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 45),
                    bgColor: EsColors.Primary,
                    textColor: EsColors.White,
                    onTap: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  /// 获取抽奖机会
  static void showAchieveChance(BuildContext context,
      {List info, ClickCallback clickCallback}) {
    YpShowDialog.dialog(
        context,
        Container(
          width: double.infinity,
          height: 235,
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 25),
          alignment: Alignment.center,
          decoration: EsDecoration.BoxShadowWithRadius,
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '获取抽奖机会',
                  style: TextStyle(
                      fontSize: EsSizes.XL,
                      color: EsColors.Title,
                      fontWeight: EsFontWeights.Medium),
                ),
                Expanded(child: SizedBox()),
                _achieveChanceItem('还可以使用积分兑换3次', '兑换', () {
                  print('兑换');
                  Navigator.of(context).pop();
                }),
                Expanded(child: SizedBox()),
                _achieveChanceItem('还可以分享获取一次', '分享', () {
                  print('分享');
                  Navigator.of(context).pop();
                }),
                Expanded(child: SizedBox()),
                _achieveChanceItem('还可以下单获取1次', '去下单', () {
                  print('去下单');
                  Navigator.of(context).pop();
                }),
                Expanded(child: SizedBox()),
              ],
            ),
          ),
        ));
  }

  /// 恭喜中奖励
  static void showCongratulations(
      BuildContext context, Map rewardInfo, Callback callBack) {
    YpShowDialog.dialog(
        context,
        Container(
          width: 620.w,
          height: 800.w,
          padding: EdgeInsets.symmetric(horizontal: 60.w, vertical: 80.w),
          alignment: Alignment.center,
          decoration: BoxDecoration(
              image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage(
                    'assets/images/fortune_win_bg.png',
                  ))),
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Expanded(child: SizedBox()),
                Image.network(
                  rewardInfo['reward_picture_url'],
                  width: setWidth(200),
                  height: setWidth(200),
                  fit: BoxFit.cover,
                ),
                SizedBox(height: 20.w),
                Text(
                  rewardInfo['reward_level'] +
                      '\n' +
                      rewardInfo['reward_description'],
                  textAlign: TextAlign.center,
                  style: TextStyle(
                      fontSize: EsSizes.LG * 2.sp,
                      color: EsColors.White,
                      fontWeight: EsFontWeights.Medium),
                ),
                GestureDetector(
                  onTap: () async {
                    Navigator.of(context).pop();
                    Future.delayed(Duration(milliseconds: 300), () {
                      callBack();
                    });
                  },
                  child: Padding(
                    padding: EdgeInsets.only(top: 40.w),
                    child: Image.asset('assets/images/fortune_check_gift.png',
                        width: 400.w, height: 88.w, fit: BoxFit.fill),
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  /// 抱歉没中奖
  static void showSorry(BuildContext context, String picUrl) {
    YpShowDialog.dialog(
        context,
        Container(
          width: double.infinity,
          height: setWidth(500),
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 25),
          alignment: Alignment.center,
          decoration: EsDecoration.BoxShadowWithRadius,
          child: Center(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Text(
                  '抱歉，本次没有抽中哦',
                  style: TextStyle(
                      fontSize: EsSizes.XL,
                      color: EsColors.Title,
                      fontWeight: EsFontWeights.Medium),
                ),
                Expanded(child: SizedBox()),
                Image.network(
                  picUrl,
                  width: setWidth(160),
                  height: setWidth(160),
                  fit: BoxFit.contain,
                ),
                Expanded(child: SizedBox()),
                GestureDetector(
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                  child: Container(
                      width: double.infinity,
                      height: 44,
                      margin: EdgeInsets.symmetric(horizontal: 20),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topCenter,
                          end: Alignment.bottomCenter,
                          colors: [Color(0xfffde8a3), Color(0xffffac35)],
                        ),
                        borderRadius: BorderRadius.all(Radius.circular(55)),
                      ),
                      child: Text(
                        '再试试吧',
                        style: TextStyle(
                            fontSize: EsSizes.LG,
                            color: Color(0xff9a0201),
                            fontWeight: EsFontWeights.Medium),
                      )),
                ),
                Expanded(child: SizedBox()),
              ],
            ),
          ),
        ));
  }

  /// 活动规则
  static void showActivitiesRule(BuildContext context) {
    YpShowDialog.dialog(
        context,
        Material(
            type: MaterialType.transparency,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  decoration: BoxDecoration(
                      color: EsColors.White,
                      borderRadius: BorderRadius.all(Radius.circular(10))),
                  padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                  margin: EdgeInsets.symmetric(horizontal: 15),
                  child: Column(
                    children: [
                      Center(
                        child: Text('活动规则',
                            style: TextStyle(
                                color: EsColors.Title,
                                fontSize: EsSizes.MD,
                                fontWeight: EsFontWeights.Medium)),
                      ),
                      Container(
                        constraints: BoxConstraints(
                            minHeight: MediaQuery.of(context).size.height / 3,
                            maxHeight: MediaQuery.of(context).size.height / 2),
                        child: ListView(
                          shrinkWrap: true,
                          children: [
                            SizedBox(height: 18),
                            Text(
                              '活动规则',
                              style: TextStyle(
                                  color: EsColors.TitleSecondary,
                                  fontSize: EsSizes.XS,
                                  fontWeight: EsFontWeights.Normal),
                            ),
                            SizedBox(height: 18),
                          ],
                        ),
                        // width: 200,
                        // height: 200,
                        color: EsColors.White,
                      ),
                    ],
                  ),
                ),
                IconButton(
                  alignment: Alignment.center,
                  padding: const EdgeInsets.all(0.0),
                  splashColor: Colors.transparent,
                  highlightColor: Colors.transparent,
                  icon: Image.asset('assets/images/common_dialog_cancel.png'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            )));
  }

  /// 参团列表
  static void showGroupList(BuildContext context) {
    final StopWatchTimer _stopWatchTimerDown = StopWatchTimer(
      mode: StopWatchMode.countDown,
      presetMillisecond: StopWatchTimer.getMilliSecFromSecond(3),

      // onChange: (value) => print('onChange $value'),
      // onChangeRawSecond: (value) => print('onChangeRawSecond $value'),
      // onChangeRawMinute: (value) => print('onChangeRawMinute $value'),
      onEnded: () {
        print('onEnded');
      },
    );
    _stopWatchTimerDown.setPresetHoursTime(11);
    _stopWatchTimerDown.setPresetMinuteTime(20);
    _stopWatchTimerDown.setPresetSecondTime(12);
    Future.delayed(Duration(milliseconds: 300), () {
      _stopWatchTimerDown.onExecute.add(StopWatchExecute.start);
    });

    YpShowDialog.dialog(
        context,
        Material(
            type: MaterialType.transparency,
            child: Container(
                decoration: BoxDecoration(
                    color: EsColors.White,
                    borderRadius: BorderRadius.all(Radius.circular(10))),
                padding: EdgeInsets.symmetric(horizontal: 10),
                constraints: BoxConstraints(
                    minHeight: MediaQuery.of(context).size.height / 3,
                    maxHeight: MediaQuery.of(context).size.height / 2),
                child: ListView.separated(
                    shrinkWrap: true,
                    itemBuilder: (context, index) {
                      return Row(children: [
                        Padding(
                          padding: const EdgeInsets.only(top: 15, bottom: 15),
                          child: Image.asset('assets/images/group_mumber.png',
                              width: 45, height: 45, fit: BoxFit.fill),
                        ),
                        SizedBox(width: 8),
                        Text(
                          '路人甲的停滞',
                          style: TextStyle(
                              color: EsColors.TitleSecondary,
                              fontSize: EsSizes.SM,
                              fontWeight: EsFontWeights.Medium),
                        ),
                        Expanded(child: SizedBox()),
                        Column(
                          children: [
                            RichText(
                                textAlign: TextAlign.center,
                                text: TextSpan(children: [
                                  TextSpan(
                                      text: '还差',
                                      style: TextStyle(
                                          fontSize: EsSizes.XS,
                                          color: EsColors.TitleSecondary,
                                          fontWeight: EsFontWeights.Normal)),
                                  TextSpan(
                                      text: '0',
                                      style: TextStyle(
                                          fontSize: EsSizes.XS,
                                          color: EsColors.Primary,
                                          fontWeight: EsFontWeights.Normal)),
                                  TextSpan(
                                      text: '人开团成功',
                                      style: TextStyle(
                                          fontSize: EsSizes.XS,
                                          color: EsColors.TitleSecondary,
                                          fontWeight: EsFontWeights.Normal)),
                                ])),
                            StreamBuilder<int>(
                              stream: _stopWatchTimerDown.rawTime,
                              initialData: _stopWatchTimerDown.rawTime.value,
                              builder: (context, snap) {
                                final value = snap.data;
                                final displayTime =
                                    StopWatchTimer.getDisplayTime(value,
                                        hours: true, milliSecond: false);
                                return Row(
                                  children: [
                                    Text('剩余',
                                        style: TextStyle(
                                            fontSize: EsSizes.XS,
                                            color: EsColors.Content,
                                            fontWeight: EsFontWeights.Normal)),
                                    SizedBox(
                                      width: 50,
                                      child: Center(
                                        child: Text(displayTime,
                                            style: TextStyle(
                                                fontSize: EsSizes.XS,
                                                color: EsColors.Content,
                                                fontWeight:
                                                    EsFontWeights.Normal)),
                                      ),
                                    ),
                                    Text('结束',
                                        style: TextStyle(
                                            fontSize: EsSizes.XS,
                                            color: EsColors.Content,
                                            fontWeight: EsFontWeights.Normal)),
                                  ],
                                );
                              },
                            ),
                          ],
                        ),
                        SizedBox(width: 8),
                        EsOutLineButton(
                          '去参团',
                          bgColor: EsColors.Primary,
                          textColor: EsColors.White,
                          fontSize: EsSizes.MD,
                          fontWeight: EsFontWeights.Medium,
                          padding:
                              EdgeInsets.symmetric(vertical: 6, horizontal: 12),
                          borderRadius: 18,
                          onTap: () {
                            print('去参团');
                            Navigator.of(context).pop();
                          },
                        )
                      ]);
                    },
                    separatorBuilder: (context, index) {
                      return YpLine();
                    },
                    itemCount: 10))),
        padding: const EdgeInsets.symmetric(horizontal: 10));
  }
}

/// 获取抽奖机会的item
Widget _achieveChanceItem(String title, String btnTitle, Function onTap) {
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceBetween,
    children: [
      Text(
        title ?? '',
        style: TextStyle(
            fontSize: EsSizes.SM,
            color: EsColors.Title,
            fontWeight: EsFontWeights.Normal),
      ),
      GestureDetector(
        onTap: onTap,
        child: Container(
            width: 80,
            height: 32,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xfffde8a3), Color(0xffffac35)],
              ),
              borderRadius: BorderRadius.all(Radius.circular(55)),
            ),
            child: Text(
              btnTitle ?? '',
              style: TextStyle(
                  fontSize: EsSizes.SM,
                  color: Color(0xff9a0201),
                  fontWeight: EsFontWeights.Medium),
            )),
      )
    ],
  );
}

WidgetSpan _buildCenteredTextSpan(
    {String text, double width, TextStyle style}) {
  return WidgetSpan(
    alignment: PlaceholderAlignment.bottom,
    child: SizedBox(width: 50, child: Text(text, style: style)),
  );
}
